package com.lm.jsqlparser.example;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.Join;

public class ExtractTableNames {

    public static void main(String[] args) throws JSQLParserException {
        String sql = "SELECT a.id, b.name FROM orders a JOIN customers b ON a.customer_id = b.id";

        // 解析 SQL
        Select selectStatement = (Select) CCJSqlParserUtil.parse(sql);
        PlainSelect plainSelect = (PlainSelect) selectStatement.getSelectBody();

        // 主表
        System.out.println("主表：" + plainSelect.getFromItem());

        // JOIN 表
        if (plainSelect.getJoins() != null) {
            for (Join join : plainSelect.getJoins()) {
                System.out.println("JOIN 表：" + join.getRightItem());
            }
        }
    }
}
